package com.intelligent.eayon.handler;

import com.intelligent.eayon.dto.RequestDto;
import com.intelligent.eayon.message.MessageHead;
import com.intelligent.eayon.message.Request;
import com.intelligent.eayon.message.TransMessage;
import com.intelligent.eayon.utils.ByteUtils;
import com.intelligent.eayon.utils.MessageUtils;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.ExceptionMessages;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ProtocolDecoderHandler extends ChannelInboundHandlerAdapter {

    private static Logger logger = LoggerFactory.getLogger(ProtocolDecoderHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        String clientIp = ctx.channel().remoteAddress().toString();
        logger.info("Received message from [{}], body:[{}]", clientIp, msg.toString());

        TransMessage message = (TransMessage) msg;
        Request request = MessageUtils.requestDecoder(message.getBody().getData());
        RequestDto requestDto = MessageUtils.requestDtoDecoder(request);

        ctx.fireChannelRead(requestDto);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        MessageHead messageHead = new MessageHead();
        byte[] error;
        if (cause instanceof ApplicationException) {
            error = ByteUtils.intToBytes(((ApplicationException) cause).getCode());
        } else {
            error = ByteUtils.intToBytes(ExceptionMessages.ERR_20001);
        }
        byte[] errc = new byte[6];
        for (int i = 2; i < 6; i++) {
            errc[i] = error[i - 2];
        }
        messageHead.setErrc(errc);

        TransMessage message = MessageUtils.buildTransMessage(messageHead, null);

        logger.error("exceptionCaught from ProtocolDecoderHandler: " + cause);
        ctx.writeAndFlush(message);
        cause.printStackTrace();

    }

}
